package net.wangds.common.web.fileupload.service;

import net.wangds.common.web.fileupload.comp.FileUploadComp;
import net.wangds.common.web.fileupload.module.FileBytes;
import net.wangds.common.web.fileupload.module.FileUploadData;
import net.wangds.common.web.fileupload.module.UploadFileEntity;
import net.wangds.common.web.fileupload.viewmodel.form.FileUploadForm;
import net.wangds.jdbc.comp.jdbc.JdbcComp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * .
 * <p></p>
 *
 * @author 王东石 2020/5/15 12:24.
 */
@Service
public class FileUploadServ {

    @Autowired
    FileUploadComp mmCmpUpld;

    @Autowired
    JdbcComp mmJdbc;

    public Optional<UploadFileEntity> onUpload(FileUploadData form){
        if(form==null){
            return Optional.empty();
        }
        return mmCmpUpld.upload(form);
    }

    public Optional<UploadFileEntity> onUpload(FileUploadForm form){
        if(form==null){
            return Optional.empty();
        }
        return mmCmpUpld.upload(form);
    }

    public FileBytes loadFile(String fileid){
        return mmCmpUpld.loadFile(fileid);
    }

    /**
     * 返回id列表中的文件信息.
     * @param ids id列表.
     * @return 文件信息列表.
     */
    public List<UploadFileEntity> findInIds(List<String> ids){
        StringBuilder sql = new StringBuilder();
        sql.append("SELECT * FROM ").append(UploadFileEntity.TABLE_NAME)
                .append(" WHERE id in (");
        ids.forEach(id->sql.append("?,"));
        sql.deleteCharAt(sql.length()-1);
        sql.append(")");
        Object[] args = new Object[ids.size()];
        args = ids.toArray(args);
        return mmJdbc.executeQuery(sql.toString(), args, UploadFileEntity.class);
    }

}
